/**
 * Created by Blink on 2017/7/13.
 * scss var to map
 */

const fs = require('fs');

const scssPath = './icon/variables.scss';
const mapPath = './src/icon.maps.js';
const fontPath = './icon/fonts/icomoon.ttf';
const androidAsset = '../../android/app/src/main';

fs.readFile(scssPath, (err, data) => {
    if (err) console.error(err);
    else {
        let src = data.toString();
        src = src.substr(src.indexOf('\n')+1);
        src = src.replace(/\$icon-/g, '\t"').replace(/:/g, '":')
            .replace(/\\/g, '\\u').replace(/";/g, '",');

        fs.open(mapPath, 'w+', (err, fd) => {
            if (err) console.error(err);
            else {
                const str = 'const maps = {\n' + src +  '};\nexport default maps;'

                fs.write(fd, str, 0, str.length, 0, () => {
                    fs.close(fd);
                    console.log('done.');
                })
            }
        })
    }
});


// TODO: if not exist will create.
function checkDir(path) {
    return new Promise((res, rej) => {
        fs.stat(path, (err, stat) => {
            if (err || stat.isFile()) {
                fs.mkdir(path, (err) => {
                    if (err) rej(err);
                    else res();
                })
            } else {
                res();
            }
        })
    })
}

fs.readFile(fontPath, (err, data) => {
    // data = data.toString();
    const writeFile = () => {
        fs.open(androidAsset + '/assets/fonts/blinkIcon.ttf', 'w+', (err, fd) => {
            if (err) console.error(err);
            else {
                fs.write(fd, data, 0, data.length, 0, () => {
                    fs.close(fd);
                    console.log('copy fonts to android assets/fonts');
                })
            }
        })
    };

    if (err) console.error(err);
    else {
        checkDir(androidAsset + '/assets').then(() => {
            checkDir(androidAsset + '/assets/fonts').then(() => {
                writeFile();
            }).catch((e) => console.error(e))
        }).catch((e) => console.error(e))
    }
});

